import React from 'react';
import { Button, Modal, message } from 'antd';
import {
    WeaErrorPage,
    WeaTools,
    WeaInput,
    WeaDialog,
    WeaRightMenu,
    WeaRichText,
    WeaUpload,
    WeaLocaleProvider
} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

class AddNotice extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            isView: false,
            id: '',
            title: '',
            imgsrc: '',
            content: '',
            isNew: true
        }
        this.onSetState = this.onSetState.bind(this);
        this.getButtons = this.getButtons.bind(this);
        this.getRightMenu = this.getRightMenu.bind(this);
        this.onRightMenuClick = this.onRightMenuClick.bind(this);
        this.onUploadChange = this.onUploadChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.onDel = this.onDel.bind(this);
        this.onCancel = this.onCancel.bind(this);
    }
    onSetState(state){
        this.setState(state);
    }

    onDel(){
        Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(15097, '确定要删除吗？'),
            onOk: () => {
                WeaTools.callApi('/api/portal/noticeadd/delNotice', 'POST', { id: this.state.id }).then(result=> {
                    if(result.status == '2'){
                        message.error(result.errormsg);
                    }else{
                        message.success(getLabel(83472, "删除成功！"));
                        this.props.handleRefresh();
                        this.setState({visible:false});
                    }
                });
            },
        });
    }
    getButtons(){
        let btns = [];
        if(this.props.canAddNotice){
          if(this.state.isView){
              btns.push(<Button type="primary" onClick={this.onSetState.bind(this,{isNew: false, isView:false})}>{getLabel(26473, '编辑')}</Button>);
              btns.push(<Button onClick={this.onDel}>{getLabel(	91, '删除')}</Button>)
          }else{
              btns.push(<Button type="primary" onClick={this.handleSubmit}>{getLabel(826, '确定')}</Button>);
          }
        }
        btns.push(<Button onClick={this.onSetState.bind(this,{isNew: false, visible: false, id: '', title: '',imgsrc: '', content: '',})}>{getLabel(31129, '取消')}</Button>)
        return btns
    }
    getRightMenu(){
        let btns = [];
        if(this.props.canAddNotice){
            if(this.state.isView){
              btns.push({
                icon: <i className='icon-coms-Preservation'/>,
                key: 'edit',
                content:getLabel(26473, '编辑')
              });
              btns.push({
                  icon: <i className='icon-coms-go-back'/>,
                  key: 'del',
                  content:getLabel(	91, '删除')
              });
            }else{
              btns.push({
                icon: <i className='icon-coms-Preservation'/>,
                key: 'save',
                content:getLabel(30986, '保存')
              });
            }
        }
        btns.push({
            icon: <i className='icon-coms-go-back'/>,
            key: 'cancel',
            content:getLabel(31129, '取消')
        });   
        return btns
    }
    onUploadChange(ids,lists){
      if(lists[lists.length - 1]){
          this.setState({
              imgsrc: lists[0].filelink,
          });
      }
    }
    onRightMenuClick(key){
        switch(key){
            case 'edit':
                this.onSetState({isNew: true, isView:false});
                break;
            case 'del':
                this.onDel();
                break;
            case 'save':
                this.handleSubmit();
                break;
            case 'cancel':
                this.onCancel();
                break;
        }
    }
    handleSubmit(){
        const { id, title, content, imgsrc, isView, isNew } = this.state;
        const { eid, handleRefresh } = this.props;
        if(!title.trim()){
           Modal.error({
              title: getLabel(15172, '系统提示'),
              content:getLabel(388025,"标题不能为空")
           });
           return;
        }
        // if(!content.trim()){
        //     Modal.error({
        //         title: getLabel(15172, '系统提示'),
        //         content:getLabel(388025,"内容不能为空")
        //     });
        //     return;
        // }
        if(!imgsrc.trim()){
           Modal.error({
              title: getLabel(15172, '系统提示'),
              content: getLabel(388026,"图片不能为空")
           });
           return;
        }
        WeaTools.callApi('/api/portal/noticeadd/addNotice', 'POST', {id, eid, title, content, imgsrc }).then(result=> {
            if(result.status == '2'){
                message.error(result.errormsg);
            }else{
                if(isNew){
                    message.success(getLabel(83880,"添加成功！"));
                }else if(!isNew){
                    message.success(getLabel(387621,"修改成功！"));
                }
                handleRefresh();
                this.setState({visible:false});
                this.onCancel();
            }
        });
    }

    onCancel(){
        this.onSetState({visible: false, id: '', title: '',imgsrc: '', content: '',});
    }

    render() {
        const { visible, isView, id, title, content, imgsrc  } = this.state;
        return <WeaDialog title={isView ?getLabel(388027,"查看公告"): (id ? getLabel(388028,"编辑公告") : getLabel(131679,"发布公告"))}
                  visible={visible} 
                  closable={true}
                  onCancel={this.onSetState.bind(this,{visible: false, id: '', title: '',imgsrc: '', content: '',})}
                  icon='icon-coms-portal'
                  iconBgcolor='#1a57a0'
                  maskClosable={false}
                  buttons={this.getButtons()}
                  style={{width: 694, height: 615}}>
                  <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                    {isView ? <div style={{overflow: 'auto', maxHeight: '100%', maxWidth: '100%',margin:'20px'}} dangerouslySetInnerHTML={{__html: content}}/> :
                    <div className="newnotice-add-container">
                      <div className="newnotice-add-picture">
                            <WeaUpload
                              ref={imgsrc}
                              uploadId="noticeUpload"
                              maxFilesNumber='1'
                              uploadUrl="/api/portal/noticeadd/uploadImg"
                              category="0"
                              viewAttr="2"
                              multiSelection={false}
                              limitType="png,gif,jpeg,jpg,bmp"
                              onChange={this.onUploadChange}
                              showClearAll={true}>
                              <div className="newnotice-add-picture-icon">
                                  <img className={imgsrc ? "portal-element-newnotice-add-img" : "portal-element-newnotice-add-icon"} src={imgsrc || "/page/element/newNotice/resource/image/new.png"} title={getLabel(124841,"添加图片")} alt=""/>
                              </div>
                            </WeaUpload>
                            <div className="newnotice-add-picture-tip">{getLabel(388029,"建议尺寸:900像素*500像素")}</div>
                      </div>
                      <div className="newnotice-add-title">
                          <div className="newnotice-add-name">
                              {getLabel(24986, '标题')}
                          </div>
                          <div className="newnotice-add-name">
                              <WeaInput viewAttr={3} value={title} onChange={value=>this.onSetState({title: value})}/>
                          </div>
                      </div>
                      <div className="newnotice-add-text">
                          <div className="newnotice-add-name">
                              {getLabel(1265,"正文")}
                          </div>
                          <WeaRichText
                              ref="WeaRichText"
                              value={content}
                              ckConfig={{
                                  toolbar: [
                                      {name: 'document', items: ['Source']},
                                      {name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike']},
                                      {name: 'styles', items: ['Format', 'Font', 'FontSize']},
                                      {name: 'colors', items: ['TextColor', 'BGColor']},
                                      {name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']},
                                      {name: 'links', items: ['Link', 'Unlink', 'Anchor']},
                                      {name: 'insert', items: ['Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar']},
                                      {name: 'clipboard', items: ['Undo', 'Redo']},
                                      {name: 'tools', items: ['Maximize']}
                                  ],
                                  extraPlugins: 'autogrow',
                                  height: 300,
                                  autoGrow_minHeight: 300,
                                  autoGrow_maxHeight: 300,
                                  removePlugins: 'resize',
                                  uploadUrl: '/api/portal/fileupload/uploadfile',
                              }}
                              onChange={value => this.onSetState({content: value})}
                          />
                      </div>
                    </div>}
                </WeaRightMenu>
        </WeaDialog>
    }
}
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
            return ( <WeaErrorPage msg = { hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
AddNotice = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(AddNotice);
export default AddNotice;